package com.example.cs4;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;

import java.awt.Desktop;
import java.net.URI;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@SpringBootApplication
@MapperScan("com.example.cs4.mapper")
@EnableCaching
public class Cs4Application {

    public static void main(String[] args) {
        SpringApplication.run(Cs4Application.class, args);
    }

    @Bean
    public CommandLineRunner commandLineRunner() {
        return args -> {
            // 使用线程在应用启动后打开默认浏览器并导航到指定网址
            new Thread(() -> {
                try {
                    if (java.awt.GraphicsEnvironment.isHeadless()) {
                        // 在无头模式下使用命令行打开浏览器
                        String url = "http://localhost:8080/";
                        Runtime runtime = Runtime.getRuntime();
                        if (System.getProperty("os.name").toLowerCase().contains("win")) {
                            runtime.exec("rundll32 url.dll,FileProtocolHandler " + url);
                        } else if (System.getProperty("os.name").toLowerCase().contains("mac")) {
                            runtime.exec("open " + url);
                        } else {
                            // 假设是类 Unix 系统
                            String[] browsers = {"firefox", "chrome", "safari", "opera", "konqueror", "epiphany", "mozilla"};
                            StringBuffer cmd = new StringBuffer();
                            for (String browser : browsers) {
                                cmd.append((cmd.length() == 0 ? "" : " || ") + browser + " \"" + url + "\" ");
                            }
                            runtime.exec(new String[]{"sh", "-c", cmd.toString()});
                        }
                    } else {
                        Desktop.getDesktop().browse(new URI("http://localhost:8080/"));
                    }
                } catch (Exception e) {
                    logger.error("Failed to open browser", e);
                }
            }).start();
        };
    }

    private static final Logger logger = LoggerFactory.getLogger(Cs4Application.class);
}
